package com.xiao.hao.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import org.apache.tomcat.util.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.List;

public class ParamsAesUtils {

    private static final List RANDOWList_AES_KEY = Lists.newArrayList(
            "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");


    private static final String ALGORITHMSTR = "AES/CBC/PKCS7Padding";

    private static final String KEY_ALGORITHM = "AES";


    static {
        Security.addProvider(new BouncyCastleProvider());
    }


    public static String encrypt(String content, String key, String ivPara) {
        String encryptStr = "";
        try {
            encryptStr =
                    Base64.encodeBase64String(getCipher(key, ivPara, Cipher.ENCRYPT_MODE).doFinal(content.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptStr;
    }

    public static String decrypt(String content, String key, String ivPara) {
        String decryptStr = "";

        try {
            decryptStr = new String(getCipher(key, ivPara, Cipher.DECRYPT_MODE).doFinal(Base64.decodeBase64(content))
                    , StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptStr;
    }


    private static Cipher getCipher(String key, String ivParameter, int encryptMode) {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(ALGORITHMSTR);
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(encryptMode, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), KEY_ALGORITHM), iv);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cipher;
    }

    public static String getAesKey() {
        return StrUtil.join("", RandomUtil.randomEleSet(RANDOWList_AES_KEY, 16));
    }

    public static String getLengthKey(Integer length) {
        return StrUtil.join("", RandomUtil.randomEleSet(RANDOWList_AES_KEY, length));
    }
}
